import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../theme/app_theme.dart';

import '../services/app_notifier_provider.dart';
import '../models/period_model.dart';
import '../widgets/record_dialog.dart';
import '../widgets/calendar_widget.dart';

import 'month_selection_screen.dart';
import '../utils/error_handler.dart';
import '../utils/error_display.dart';

import 'pregnancy_preparation_screen.dart';

class RecordScreen extends StatefulWidget {
  const RecordScreen({super.key});

  @override
  State<RecordScreen> createState() => _RecordScreenState();
}

class _RecordScreenState extends State<RecordScreen> {
  List<PeriodModel> _monthData = [];
  final List<String> _weekdays = ['日', '一', '二', '三', '四', '五', '六'];
  final List<String> _tabs = ['经期', '备孕', '怀孕', '育儿'];
  int _currentTabIndex = 0;
  DateTime _currentDate = DateTime.now();
  DateTime? _selectedDate; 

  bool _isLoading = false; 


  @override
  void initState() {
    super.initState();
    _startPeriodStatusListener();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    
    if (_monthData.isEmpty) {
      _loadData();
    }
  }

  void _startPeriodStatusListener() {
    
    Future.delayed(const Duration(seconds: 2), () async {
      final prefs = await SharedPreferences.getInstance();
      final lastChange = prefs.getInt('lastPeriodStatusChange') ?? 0;
      final now = DateTime.now().millisecondsSinceEpoch;

      
      if (now - lastChange < 30000) {
        if (mounted) {
          _loadData();
          
          await prefs.setBool('periodStatusChanged', false);
        }
      }

      
      if (mounted) {
        _startPeriodStatusListener();
      }
    });
  }

  Future<void> _loadData() async {
    try {
      setState(() {
        _isLoading = true;
      });
      
      
      final appState = AppNotifierProvider.of(context);
      final monthData = await appState.getMonthData(_currentDate);

      
      await Future.delayed(const Duration(milliseconds: 300));
      
      setState(() {
        _monthData = monthData;
        _isLoading = false;
      });
    } catch (e) {
      
      final errorHandler = ErrorHandler();
      final appError = errorHandler.handleError(e, '_loadData');
      
      setState(() {
        _monthData = [];
        _isLoading = false;
      });
      
      ErrorDisplay.showErrorWithRetry(
        context,
        appError,
        () => _loadData(),
      );
    }
  }

  

  void _goToMonthSelection() async {
    
    final DateTime? selectedDate = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => MonthSelectionScreen(
          selectedDate: _currentDate,
          onDateSelected: (date) {
            setState(() {
              _currentDate = date;
              _selectedDate = null; 

            });
            _loadData();
          },
        ),
      ),
    );

    
    if (selectedDate != null) {
      setState(() {
        _currentDate = selectedDate;
        _selectedDate = null; 

      });
      _loadData();
    }
  }

  
  void _goToPreviousMonth() async {
    
    setState(() {
      _currentDate = DateTime(_currentDate.year, _currentDate.month - 1, 1);
      _selectedDate = null; 

    });
    await _loadData();
  }

  
  void _goToNextMonth() async {
    
    setState(() {
      _currentDate = DateTime(_currentDate.year, _currentDate.month + 1, 1);
      _selectedDate = null; 

    });
    await _loadData();
  }
  
  

  
  void _onDateTap(DateTime date) {
    
    if (date.day == 1 && date.hour == 0 && date.minute == 0 && date.second == 0) {
      
      setState(() {
        _currentDate = date;
        _selectedDate = null; 

      });
      
      _loadData(); 

    } else {
      
      setState(() {
        _selectedDate = date;
      });

      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('已选择日期: ${date.year}年${date.month}月${date.day}日'),
          duration: const Duration(seconds: 1),
          behavior: SnackBarBehavior.floating,
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppTheme.background,
      appBar: AppBar(
        backgroundColor: AppTheme.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: _goToMonthSelection,
          color: AppTheme.textPrimary,
        ),
        title: const Text(''),
        actions: [
          IconButton(
            icon: Icon(Icons.bar_chart),
            onPressed: () => Navigator.pushNamed(context, '/health_report'),
            color: AppTheme.textPrimary,
          ),
        ],
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              
              Container(
                padding:
                    const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                color: AppTheme.white,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: List.generate(_tabs.length, (index) {
                    return GestureDetector(
                      onTap: () {
                        setState(() {
                          _currentTabIndex = index;
                        });

                        
                        switch (index) {
                          case 1: 

                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => PregnancyPreparationScreen(),
                              ),
                            );
                            break;
                          case 2: 

                            Navigator.pushNamed(context, '/pregnancy_mode');
                            break;
                          case 3: 

                            Navigator.pushNamed(context, '/parenting_mode');
                            break;
                          case 0: 

                          default:
                            
                            break;
                        }
                      },
                      child: Text(
                        _tabs[index],
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: _currentTabIndex == index
                              ? FontWeight.bold
                              : FontWeight.normal,
                          color: _currentTabIndex == index
                              ? AppTheme.primaryColor
                              : AppTheme.textSecondary,
                        ),
                      ),
                    );
                  }),
                ),
              ),

              
              Container(
                margin: const EdgeInsets.only(top: 8),
                padding:
                    const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                color: AppTheme.white,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        IconButton(
                          icon: const Icon(Icons.chevron_left),
                          onPressed: () => _goToPreviousMonth(),
                          color: AppTheme.textPrimary,
                        ),
                        GestureDetector(
                          onTap: () => _goToMonthSelection(),
                          child: Text(
                            '${_currentDate.year}年${_currentDate.month}月',
                            style: const TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                              color: AppTheme.textPrimary,
                            ),
                          ),
                        ),
                        IconButton(
                          icon: const Icon(Icons.chevron_right),
                          onPressed: () => _goToNextMonth(),
                          color: AppTheme.textPrimary,
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),
                    
                    Row(
                      children: List.generate(7, (index) {
                        return Expanded(
                          child: Text(
                            _weekdays[index],
                            textAlign: TextAlign.center,
                            style: const TextStyle(
                              fontSize: 14,
                              color: AppTheme.textSecondary,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        );
                      }),
                    ),
                    const SizedBox(height: 8),

                    
                    _buildCalendarGrid(),
                  ],
                ),
              ),

              
              Container(
                margin: const EdgeInsets.only(top: 8),
                padding: const EdgeInsets.all(16),
                color: AppTheme.white,
                child: Column(
                  children: [
                    
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: const [
                            Icon(Icons.mood_bad,
                                size: 20, color: Color(0xFF9C27B0)),
                            SizedBox(width: 10),
                            Text('痛经', style: AppTheme.bodyStyle),
                          ],
                        ),
                        IconButton(
                          icon: const Icon(Icons.add),
                          onPressed: () => _showRecordDialog('cramps', '痛经',
                              Icons.mood_bad, const Color(0xFF9C27B0)),
                          color: AppTheme.primaryColor,
                        ),
                      ],
                    ),
                    
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: const [
                            Icon(Icons.favorite,
                                size: 20, color: Color(0xFFEC407A)),
                            SizedBox(width: 10),
                            Text('爱爱', style: AppTheme.bodyStyle),
                          ],
                        ),
                        IconButton(
                          icon: const Icon(Icons.add),
                          onPressed: () => _showRecordDialog('intercourse',
                              '爱爱', Icons.favorite, const Color(0xFFE91E63)),
                          color: AppTheme.primaryColor,
                        ),
                      ],
                    ),
                    
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: const [
                            Icon(Icons.medical_information,
                                size: 20, color: Color(0xFF00BCD4)),
                            SizedBox(width: 10),
                            Text('症状', style: AppTheme.bodyStyle),
                          ],
                        ),
                        IconButton(
                          icon: const Icon(Icons.add),
                          onPressed: () => _showRecordDialog(
                              'symptoms',
                              '症状',
                              Icons.medical_information,
                              const Color(0xFF00BCD4)),
                          color: AppTheme.primaryColor,
                        ),
                      ],
                    ),
                    
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: const [
                            Icon(Icons.mood,
                                size: 20, color: Color(0xFFFFD54F)),
                            SizedBox(width: 10),
                            Text('心情', style: AppTheme.bodyStyle),
                          ],
                        ),
                        Row(
                          children: const [
                            
                            Padding(
                              padding: EdgeInsets.symmetric(horizontal: 4),
                              child: Text('😊', style: TextStyle(fontSize: 20)),
                            ),
                            Padding(
                              padding: EdgeInsets.symmetric(horizontal: 4),
                              child: Text('😞', style: TextStyle(fontSize: 20)),
                            ),
                            Padding(
                              padding: EdgeInsets.symmetric(horizontal: 4),
                              child: Text('😣', style: TextStyle(fontSize: 20)),
                            ),
                            Padding(
                              padding: EdgeInsets.symmetric(horizontal: 4),
                              child: Text('😭', style: TextStyle(fontSize: 20)),
                            ),
                          ],
                        ),
                        IconButton(
                          icon: const Icon(Icons.add),
                          onPressed: () => _showRecordDialog('mood', '心情',
                              Icons.mood, const Color(0xFFFFD54F)),
                          color: AppTheme.primaryColor,
                          padding: EdgeInsets.zero,
                          iconSize: 20,
                        ),
                      ],
                    ),
                    
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: const [
                            Icon(Icons.invert_colors,
                                size: 20, color: Color(0xFF8BC34A)),
                            SizedBox(width: 10),
                            Text('白带', style: AppTheme.bodyStyle),
                          ],
                        ),
                        IconButton(
                          icon: const Icon(Icons.add),
                          onPressed: () => _showRecordDialog('discharge', '白带',
                              Icons.invert_colors, const Color(0xFF8BC34A)),
                          color: AppTheme.primaryColor,
                        ),
                      ],
                    ),

                    
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: const [
                            Icon(Icons.monitor_weight,
                                size: 20, color: Color(0xFF795548)),
                            SizedBox(width: 10),
                            Text('体重', style: AppTheme.bodyStyle),
                          ],
                        ),
                        IconButton(
                          icon: const Icon(Icons.add),
                          onPressed: () => _showRecordDialog('weight', '体重',
                              Icons.monitor_weight, const Color(0xFF795548)),
                          color: AppTheme.primaryColor,
                        ),
                      ],
                    ),

                    
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: const [
                            Icon(Icons.book,
                                size: 20, color: Color(0xFF607D8B)),
                            SizedBox(width: 10),
                            Text('日记', style: AppTheme.bodyStyle),
                          ],
                        ),
                        IconButton(
                          icon: const Icon(Icons.add),
                          onPressed: () => _showRecordDialog('diary', '日记',
                              Icons.book, const Color(0xFF607D8B)),
                          color: AppTheme.primaryColor,
                        ),
                      ],
                    ),

                    
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: const [
                            Icon(Icons.thumb_up,
                                size: 20, color: Color(0xFF4CAF50)),
                            SizedBox(width: 10),
                            Text('好习惯', style: AppTheme.bodyStyle),
                          ],
                        ),
                        IconButton(
                          icon: const Icon(Icons.add),
                          onPressed: () => _showRecordDialog('habit', '好习惯',
                              Icons.thumb_up, const Color(0xFF4CAF50)),
                          color: AppTheme.primaryColor,
                        ),
                      ],
                    ),

                    
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: const [
                            Icon(Icons.calendar_today,
                                size: 20, color: Color(0xFF2196F3)),
                            SizedBox(width: 10),
                            Text('计划', style: AppTheme.bodyStyle),
                          ],
                        ),
                        IconButton(
                          icon: const Icon(Icons.add),
                          onPressed: () => _showRecordDialog('plan', '计划',
                              Icons.calendar_today, const Color(0xFF2196F3)),
                          color: AppTheme.primaryColor,
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  
  Widget _buildCalendarGrid() {
    if (_isLoading) {
      return Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children:
            [CircularProgressIndicator(color: Theme.of(context).primaryColor),
             const SizedBox(height: 16),
             const Text('加载中...')
            ]
        ),
      );
    }
    
    if (_monthData.isEmpty) {
      return _buildEmptyCalendar();
    }

    
    return CalendarWidget(
      data: _monthData,
      currentDate: _currentDate,
      selectedDate: _selectedDate,
      onDateTap: _onDateTap,
      primaryColor: Theme.of(context).primaryColor,
      primaryLightColor: Theme.of(context).primaryColorLight,
      
      textPrimaryColor: Theme.of(context).textTheme.bodyLarge?.color ?? AppTheme.textPrimary,
      textLightColor: Theme.of(context).textTheme.bodySmall?.color ?? AppTheme.textLight,
      whiteColor: Colors.white,
    );
  }

  
  Widget _buildEmptyCalendar() {
    
    final List<DateTime> emptyDays = [];
    
    final firstDayOfMonth = DateTime(_currentDate.year, _currentDate.month, 1);
    final firstDayOfWeek = firstDayOfMonth.weekday; 


    
    for (int i = firstDayOfWeek - 1; i > 0; i--) {
      emptyDays.add(DateTime(_currentDate.year, _currentDate.month, 1)
          .subtract(Duration(days: i)));
    }

    
    final daysInMonth =
        DateTime(_currentDate.year, _currentDate.month + 1, 0).day;
    for (int i = 1; i <= daysInMonth; i++) {
      emptyDays.add(DateTime(_currentDate.year, _currentDate.month, i));
    }

    
    int remainingDays = (42 - emptyDays.length).clamp(0, 42);
    for (int i = 1; i <= remainingDays; i++) {
      emptyDays.add(DateTime(_currentDate.year, _currentDate.month + 1, i));
    }

    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 7,
        mainAxisSpacing: 8,
        crossAxisSpacing: 8,
      ),
      itemCount: emptyDays.length,
      itemBuilder: (context, index) {
        Color? backgroundColor;
        Color? textColor = AppTheme.textPrimary;
        double? fontSize = 16;
        int dayNumber = 0;
        bool isCurrentMonth = true;
        bool isToday = false;

        final currentDate = emptyDays[index];
        dayNumber = currentDate.day;

        
        isCurrentMonth = currentDate.month == _currentDate.month;

        
        final now = DateTime.now();
        isToday = currentDate.year == now.year &&
            currentDate.month == now.month &&
            currentDate.day == now.day;

        
        if (!isCurrentMonth) {
          textColor = AppTheme.textLight;
          fontSize = 14;
        } else if (isToday) {
          backgroundColor = AppTheme.primaryColor;
          textColor = AppTheme.white;
        }

        final displayDate = currentDate;

        return GestureDetector(
          onTap: () => _onDateTap(displayDate),
          child: Container(
            height: 40,
            decoration: BoxDecoration(
              color: backgroundColor,
              borderRadius: BorderRadius.circular(20),
              border: Border.all(
                color: isToday ? AppTheme.primaryColor : Colors.transparent,
                width: isToday ? 2 : 0,
                style: BorderStyle.solid,
              ),
            ),
            child: Center(
              child: Text(
                '$dayNumber',
                style: TextStyle(
                  color: textColor,
                  fontSize: fontSize,
                ).copyWith(
                  fontWeight: isToday ? FontWeight.bold : FontWeight.normal,
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  
  void _showRecordDialog(
      String type, String title, IconData icon, Color color) {
    showDialog(
      context: context,
      builder: (BuildContext context) => RecordDialog(
        recordType: type,
        title: title,
        icon: icon,
        iconColor: color,
        selectedDate: _selectedDate ?? DateTime.now(),
      ),
    ).then((result) async {
      try {
        if (result == true) {
          // 刷新数据
          await _loadData();
          
          // 显示成功提示
          ErrorDisplay.showSuccessSnackbar(
            context,
            '记录已保存',
          );
        } else if (result != null) {
          // 其他情况也刷新数据
          await _loadData();
        }
      } catch (e) {
        // 错误处理
        final errorHandler = ErrorHandler();
        final appError = errorHandler.handleError(e, '_showRecordDialog');
        
        // 显示错误提示
        ErrorDisplay.showErrorWithRetry(
          context,
          appError,
          () => _showRecordDialog(type, title, icon, color),
        );
      }
    });
  }
}
